<?php
/**
 * Excel导入处理类
 * @copyright   2012 友拓软件友拓通
 * @category   	Excel导入处理类
 * @package  	Model
 * @author    	吴乔源
 * @version 	2.1
 */
class AbsExcelPublicModel extends RelationCommonModel  {

	public $function_model	=	array();
	public $newModel		=	array();
	public $excel_max_row	=	999;
	public $insert_type		=	1;
	
	/**
	 * 国家插入前的规则验证
	 *
	 * @param array $date
	 * @return bool
	 */
	public function beforValidDistrict(&$date){ 
		if (!is_array($date)){  return $this->setExcelErrorMsg(0,'没有数据,请重新操作');}  
		foreach((array)$date as $key=>$value){ if (empty($value[0])){   return $this->setExcelErrorMsg(0,'国家名称必填,请重新操作'); }		} 
		return true;
	} 
	 
	
	/**
	 * 产品库存验证
	 *
	 * @param  array $date
	 * @param  array $replace
	 * @return string
	 */
	public function validStockProduct(&$date,&$replace){ 
		if (!is_array($date)){
			return $this->setExcelErrorMsg(0,'没有数据,请重新操作'); 
		}   
		$model	=	M('Product');
		$modelC	=	M('product_color');
		$modelS	=	M('product_size');   
		foreach((array)$date as $key=>$value){    
//				echo $model->getLastSql(); 
				if ($value['product_id']<=0){ 
					$msg	=	'第'.$key.'行,产品"'.$value['product_no'].'"不存在,请重新操作';
					return $this->setExcelErrorMsg(0,$msg);  
				} 
				if (array_key_exists('color_id',$value)){
					$modelCValue	=	$modelC->where('product_id='.$value['product_id'].' and color_id='.$value['color_id'].'')->find();
					if (!is_array($modelCValue)){ 
						$msg			=	'第'.$key.'行,颜色"'.$value['color_name'].'"不存在于产品"'.$value['product_no'].'"中,请重新操作';
						return $this->setExcelErrorMsg(0,$msg);  
					} 
				} 
				if (array_key_exists('size_id',$value)){
					$modelSValue	=	$modelS->where('product_id='.$value['product_id'].' and size_id='.$value['size_id'])->find(); 
					if (!is_array($modelSValue)){ 
						$msg			=	'第'.$key.'行,尺码"'.$value['size_name'].'"不存在于产品"'.$value['product_no'].'"中,请重新操作';
						return $this->setExcelErrorMsg(0,$msg);   
					}
				}
				unset($modelSValue);
				unset($modelCValue);  
		}  
		return NULL;
	}
	
	 
	/**
	 * 导入产品预先验证规则
	 *
	 * @param array $date
	 * @param array $replace
	 * @param array $excel
	 * @return string
	 */
	public function beforValidProduct(&$date,&$replace,&$excel){
 
		///获取当前系统类别
		$findClassNameFieldNumber	=	array_search('class_name',$excel['field']); /// $key = 2; 
		$product_class_level		=	C('product_class_level');///当前系统产品级别
		$product_class				=	M('product_class');
		foreach((array)$date as $key=>$value){    
			$class_array	=	explode(',',$value[$findClassNameFieldNumber]);
			$class_array 	= 	array_diff($class_array, array(null));   ///过滤掉数组为空的数据
			if (count($class_array)!=$product_class_level){ 
				return $this->setExcelErrorMsg(0,'第'.$key.'行,数据错误请修改'); 
			}  
			///判断产品类别上下之间的关系是否正确
			if ($product_class_level>1){
				$top_class_id	=	0;	 
				///验证所有类别是否都是历史存在的还是需要新插入的
				foreach((array)$class_array as $keyc=>$valuec){  
					///判断当前类别是否已存在 
					$where			=	' class_name=\''.$valuec.'\' ';
					$info			=	$product_class->where($where)->find(); 
					///判断本级的上一级的ID是否与历史中的相符！ 如果不相同报错！
					if ($top_class_id>0 && is_array($info)){ 
						if ($info['parent_id']!=$top_class_id){
							return $this->setExcelErrorMsg(0,'第'.$key.'行,产品类别级别有误,数据错误请修改');  
						}
					} 
					if (is_array($info)){
						$top_class_id	=	$info['id']; 
					}else {
						$top_class_id	=	0; 
					} 
				}  
			}
		}
		return null; 
	}
	
	/**
	 * 员工
	 *
	 * @param array $insert_list
	 * @param object $validModel
	 */
	public function beforEmployee(&$insert_list,&$validModel){ 
		foreach((array)$insert_list as $key=>$value){    
			$insert_list[$key]['sex']			=	$value['sex']=='男'?1:2;
			$insert_list[$key]['department_id']	=	empty($value['department_name'])?0:$value['department_id']; 
			$insert_list[$key]['position_id']	=	empty($value['position_name'])?0:$value['position_id']; 
		}	 
	}
	
	/**
	 * 客户
	 *
	 * @param array $insert_list
	 * @param object $validModel
	 */
	public function beforClient(&$insert_list,&$validModel){
		foreach((array)$insert_list as $key=>$value){    
			$insert_list[$key]['remind_day']	=	empty($value['remind_day'])?0:$value['remind_day'];
			$insert_list[$key]['credit']		=	empty($value['credit'])?0:$value['credit'];
			$insert_list[$key]['contact']		=	empty($value['contact'])?'':$value['contact'];
			$insert_list[$key]['mobile']		=	empty($value['mobile'])?'':$value['mobile']; 
			$insert_list[$key]['address']		=	empty($value['address'])?'':$value['address']; 
		}
	}
	
	/**
	 * 厂家
	 *
	 * @param array $insert_list
	 * @param object $validModel
	 */
	public function beforFactory(&$insert_list,&$validModel){
		foreach((array)$insert_list as $key=>$value){    
			$insert_list[$key]['remind_day']	=	empty($value['remind_day'])?0:$value['remind_day'];
			$insert_list[$key]['credit']		=	empty($value['credit'])?0:$value['credit'];
			$insert_list[$key]['contact']		=	empty($value['contact'])?'':$value['contact'];
			$insert_list[$key]['mobile']		=	empty($value['mobile'])?'':$value['mobile']; 
			$insert_list[$key]['address']		=	empty($value['address'])?'':$value['address']; 
		}
	}
	
	/**
	 * 其他公司
	 *
	 * @param array $insert_list
	 * @param object $validModel
	 */
	public function beforOtherCompany(&$insert_list,&$validModel){
		foreach((array)$insert_list as $key=>$value){    
			$insert_list[$key]['remind_day']	=	empty($value['remind_day'])?0:$value['remind_day'];
			$insert_list[$key]['credit']		=	empty($value['credit'])?0:$value['credit'];
			$insert_list[$key]['contact']		=	empty($value['contact'])?'':$value['contact'];
			$insert_list[$key]['mobile']		=	empty($value['mobile'])?'':$value['mobile']; 
			$insert_list[$key]['address']		=	empty($value['address'])?'':$value['address']; 
		}
	} 
	
	/**
	 * 初始化库存主表信息
	 *
	 * @return unknown
	 */
	public function beforInistock(&$insert_list,&$class_form_validate){
		$model			=	M('InitStorage');
		///仓库ID
		$wInfo			=	M('warehouse')->where('is_default=1')->field('id')->find();  
		$default_w_id	=	$wInfo['id'];  
		if ($default_w_id<=0){ 
			return $this->setExcelErrorMsg(0,'请设置默认仓库,在重新导入数据');
		} 
		///验证产品规格是否符合要求 
		$copy	=	$insert_list; 
		$fruit  = 	array_shift($copy); 
		unset($copy);  
		if (array_key_exists('size_id',$fruit) || array_key_exists('color_id',$fruit)){ 
			$rinfo					=	$this->validStockProduct($insert_list);      
			if (is_array($rinfo) && $rinfo['type']==false){	return $this->setExcelErrorMsg(0,$rinfo['msg']);}
		} 
		$insert	=	array(
							'init_storage_no'		=>'',
							'init_storage_date'		=>date("Y-m-d"),
							'warehouse_id'			=>$default_w_id,
							'currency_id'			=>C('currency'),
							'create_time'			=>date("Y-m-d H:i:s"),
		);  
		$id	=	$model->add($insert); 
		 if ($id==false){ 
	  				return $this->setExcelErrorMsg(0,'主表插入错误,请重新导入'); 
		 }  
		foreach((array)$insert_list as $key=>$value){   
		 	$insert_list[$key]['init_storage_id']	=	$id;
		 	$insert_list[$key]['mantissa']			=	$value['quantity_state']=='是'?2:1;
		} 
		///验证
		$validInfo['detail']	=	$insert_list;
		$validInfo				=	array_merge($insert,$validInfo);  
		$r						= 	$class_form_validate->create($validInfo);				/// 调用验证方法   
///		$this->beforValidStock(&$validInfo);  
		if (!$r) {     
			/// 验证失败      
			return $class_form_validate->error; 
		} else {     
			///验证业务规则 
			$info=	$this->excelBrf('InitStorage','insert',&$validInfo); 
			///验证成功	  
			return $insert;
		} 
	}
	
	/**
	 * 盘点导入主表信息
	 *
	 * @return unknown
	 */
	public function beforStocktake(&$insert_list,&$class_form_validate){ 
		$model 			= M('stocktake');
		///仓库ID
		$wInfo			= M('warehouse')->where('is_default=1')->field('id')->find();
		$default_w_id	= $wInfo['id'];   
		if ($default_w_id<=0){ return $this->setExcelErrorMsg(0,'请设置默认仓库,在重新导入数据'); } 
		///验证产品规格是否符合要求 
		$copy	=	$insert_list; 
		$fruit  = 	array_shift($copy); 
		unset($copy);  
		if (array_key_exists('size_id',$fruit) || array_key_exists('color_id',$fruit)){ 
			$rinfo					=	$this->validStockProduct($insert_list);   
			if (is_array($rinfo) && $rinfo['type']==false){	return $this->setExcelErrorMsg(0,$rinfo['msg']);}  
		}   
		$insert	= array( 		'stocktake_no'			=>'',
								'stocktake_date'		=> date("Y-m-d"),
								'warehouse_id'			=> $default_w_id,
								'currency_id'			=> C('currency'),
								'employee_id'			=> 0,
								'state'					=> 1,
								'create_time'			=> date("Y-m-d H:i:s"), );
		$id	=	$model->add($insert); 
		if ($id==false){ 
	  		return $this->setExcelErrorMsg(0,'主表插入错误,请重新导入'); 
		}  
		foreach((array)$insert_list as $key=>$value){   
		 	$insert_list[$key]['stocktake_id']	=	$id;
		 	$insert_list[$key]['mantissa']			=	$value['quantity_state']=='是'?2:1;
		} 
		///验证
		$validInfo['detail']	=	$insert_list;
		$validInfo				=	array_merge($insert,$validInfo);  
		$r						= 	$class_form_validate->create($validInfo);				/// 调用验证方法   
		if (!$r) {     
			/// 验证失败      
			return $class_form_validate->error; 
		} else {     
			///验证业务规则 
			$info=	$this->excelBrf('Stocktake','insert',&$validInfo); 
			///验证成功	  
			return $insert;
		} 
	} 
	
	/**
	 * 业务规则验证
	 *
	 * @param object $m model
	 * @param object $a action
	 * @param array $insert insert info
	 */
	public function excelBrf($m,$a,&$insert){ 
		/// 业务规则检查
        $all_tags 	 	= C('extends');
        $action_tag_name = $m.'^'.$a;   
        if (isset($all_tags[$action_tag_name])) {
        	/// 添加关联类的模块信息
			$insert['_module'] = $m;
			$insert['_action'] = $a;
        	tag($action_tag_name,$insert);
        } 
	}
	
	
	/**
	 * 客户期初款项
	 *
	 * @param array $insert_list
	 * @param object $validModel
	 */
	public function beforFundclient(&$insert_list,&$validModel){  
		$valid	=	array();
		$model	=	M('client_paid_detail');  
		foreach((array)$insert_list as $key=>$value){   
			if ($value['comp_id']>0 && $value['currency_id']>0){  
				if (isset($valid[$value['comp_id']][$value['currency_id']])){  
	       			$msg	=	'第'.$key.'行,'.$value['client_name'].' 币种 '.$value['currency_name'].'重复,请重新操作';
	       			return $this->setExcelErrorMsg(0,$msg); 
				}	
				$where	=	array(
									'comp_id'=>' comp_id= '.$value['comp_id'], 
									'currency_id'=>' currency_id= '.$value['currency_id'], 
				);
				$historyInfo	=		$model->where('object_type=101 and '.join(' and ',$where))->find(); 
				if (is_array($historyInfo)){
					$msg = '第'.$key.'行,'.$value['client_name'].' '.$value['currency_name'].'已存在历史记录,请重新操作';
					return $this->setExcelErrorMsg(0,$msg);  
				} 			
			}
			$valid[$value['comp_id']][$value['currency_id']]	=	true; 
		 	$insert_list[$key]['befor_currency_id']	=	$value['currency_id'];
		 	$insert_list[$key]['base_money']		=	$value['money'];
		}   
	}
	
	
	
	/**
	 * 客户期初款项
	 *
	 * @param array $insert_list
	 */
	public function beforFundfactory(&$insert_list){ 
		$basic_info	=	M('basic')->where('is_basic=1')->find(); 
		$basic_id	=	$basic_info['id']; 
		$valid	=	array();
		$model	=	M('factory_paid_detail');
		foreach((array)$insert_list as $key=>$value){   
			if ($value['comp_id']>0 && $value['currency_id']>0){ 
				if (isset($valid[$value['comp_id']][$value['currency_id']])){  
		       			$msg	=	'第'.$key.'行,'.$value['comp_name'].' 币种 '.$value['currency_name'].'重复,请重新操作';
		       			return $this->setExcelErrorMsg(0,$msg);   
				}	
				$where	=	array( 	'comp_id'=>' comp_id= '.$value['comp_id'], 
									'currency_id'=>' currency_id= '.$value['currency_id'],);
				$historyInfo	= $model->where('object_type=201 and '.join(' and ',$where))->find(); 
				if (is_array($historyInfo)){ 
		       			$msg	=	'第'.$key.'行,'.$value['comp_name'].' '.$value['currency_name'].'已存在历史记录,请重新操作';
		       			return $this->setExcelErrorMsg(0,$msg);  
				} 			
			} 
		 	$insert_list[$key]['befor_currency_id']	=	$value['currency_id'];
		 	$insert_list[$key]['base_money']		=	$value['money'];
		 	$insert_list[$key]['basic_id']			=	$basic_id;
		 	$valid[$value['comp_id']][$value['currency_id']]	=	true;
		} 
	} 
	
	/**
	 * 导入产品后关联操作after
	 *
	 * @param array $info
	 */
	public function afterProduct($info){   
		///插入颜色
		$modelProductColor	=	M('ProductColor'); 
		$modelProductSize	=	M('ProductSize');   
		$modelProductPrice	=	M('product_price');
		$modelProductFit	=	M('product_fit');
		$modelProductDetail	=	M('product_detail');   
		$modelProduct		=	M('product');   
		$modelProductClassInfo		=	M('product_class_info');  
		$barcode			=	D('Barcode');
		foreach((array)$info['insert'] as $key=>$value){    
			$modelProductColor->where('product_id='.$value)->delete(); 
			$modelProductSize->where('product_id='.$value)->delete(); 
			$modelProductPrice->where('product_id='.$value)->delete();
			$modelProductFit->where('product_id='.$value)->delete();
			$modelProductDetail->where('product_id='.$value)->delete();    
			$modelProductClassInfo->where('product_id='.$value)->delete();    
			///类别
			$class_id	=	$modelProduct->where('id='.$value)->getField('product_class_id');    
			if ($class_id>0){ 
				///类别  
				$product_class_info	=	array('product_id'=>$value);
				$product_class_info	=	array_merge($product_class_info,$this->getProductClassInfo($class_id)); 
				$modelProductClassInfo->add($product_class_info);  
				unset($product_class_info);
			} 
			///插入颜色
			foreach((array)$info['detail']['color_name'][$key] as $kc=>$vc){   
				$colorInsert	=	array(	'product_id'=>$value,
											'color_id'=>$vc['id'], );  
				$modelProductColor->add($colorInsert); 
				unset($colorInsert);
			}
			///product_size 
			foreach((array)$info['detail']['size_name'][$key] as $ks=>$vs){   
				$sizeInsert	=	array( 		'product_id'=>$value,
											'size_id'=>$vs['id'],); 
				$modelProductSize->add($sizeInsert); 
				unset($sizeInsert);
			}
			//product_price
			$priceInsert	=	array( 	'product_id'=>$value,);
			$modelProductPrice->add($priceInsert); 
			unset($priceInsert);
			
			//product_detail
			$detailInsert	=	array( 	'product_id'=>$value,
										'properties_id'=>1,);
			$modelProductDetail->add($detailInsert); 
			unset($detailInsert);
			
			//product_fit
			$fitInsert	=	array(  'product_id'=>$value,
									'fit'=>'{&quot;1&quot;:{&quot;2&quot;:&quot;&quot;,&quot;3&quot;:&quot;&quot;,&quot;4&quot;:&quot;&quot;,&quot;5&quot;:&quot;&quot;,&quot;6&quot;:&quot;&quot;,&quot;7&quot;:&quot;&quot;,&quot;8&quot;:&quot;&quot;},&quot;2&quot;:{&quot;1&quot;:&quot;&quot;,&quot;2&quot;:&quot;&quot;,&quot;3&quot;:&quot;&quot;,&quot;4&quot;:&quot;&quot;,&quot;5&quot;:&quot;&quot;,&quot;6&quot;:&quot;&quot;,&quot;7&quot;:&quot;&quot;,&quot;8&quot;:&quot;&quot;},&quot;3&quot;:{&quot;1&quot;:&quot;&quot;,&quot;2&quot;:&quot;&quot;,&quot;3&quot;:&quot;&quot;,&quot;4&quot;:&quot;&quot;,&quot;5&quot;:&quot;&quot;,&quot;6&quot;:&quot;&quot;,&quot;7&quot;:&quot;&quot;,&quot;8&quot;:&quot;&quot;},&quot;4&quot;:{&quot;1&quot;:&quot;&quot;,&quot;2&quot;:&quot;&quot;,&quot;3&quot;:&quot;&quot;,&quot;4&quot;:&quot;&quot;,&quot;5&quot;:&quot;&quot;,&quot;6&quot;:&quot;&quot;,&quot;7&quot;:&quot;&quot;,&quot;8&quot;:&quot;&quot;},&quot;5&quot;:{&quot;1&quot;:&quot;&quot;,&quot;2&quot;:&quot;&quot;,&quot;3&quot;:&quot;&quot;,&quot;4&quot;:&quot;&quot;,&quot;5&quot;:&quot;&quot;,&quot;6&quot;:&quot;&quot;,&quot;7&quot;:&quot;&quot;,&quot;8&quot;:&quot;&quot;},&quot;6&quot;:{&quot;1&quot;:&quot;&quot;,&quot;2&quot;:&quot;&quot;,&quot;3&quot;:&quot;&quot;,&quot;4&quot;:&quot;&quot;,&quot;5&quot;:&quot;&quot;,&quot;6&quot;:&quot;&quot;,&quot;7&quot;:&quot;&quot;,&quot;8&quot;:&quot;&quot;},&quot;7&quot;:{&quot;1&quot;:&quot;&quot;,&quot;2&quot;:&quot;&quot;,&quot;3&quot;:&quot;&quot;,&quot;4&quot;:&quot;&quot;,&quot;5&quot;:&quot;&quot;,&quot;6&quot;:&quot;&quot;,&quot;7&quot;:&quot;&quot;,&quot;8&quot;:&quot;&quot;}}',
			); 
			$modelProductFit->add($fitInsert); 
			unset($fitInsert);
			///条形码
			$barcode->addBarcode($value);//生成条形码 
		}
		
	} 
	
	public  function getProductClassInfo($product_class_id) {
		$info = array();
		if (C('PRODUCT_CLASS_LEVEL')==1) {
			$info['class_1'] = $product_class_id;
		}elseif (C('PRODUCT_CLASS_LEVEL')==2) {
			$info['class_2'] = $product_class_id;
			$temp = M('ProductClass')->field('parent_id')->where($product_class_id)->find(); 
			$info['class_1'] = $temp['parent_id'];
		}elseif (C('PRODUCT_CLASS_LEVEL')==3) {
			$info['class_3'] = $product_class_id;
			$temp = M('ProductClass')->field('parent_id')->where($product_class_id)->find();
			$info['class_2'] = $temp['parent_id'];
			$temp = M('ProductClass')->field('parent_id')->where($temp['parent_id'])->find();
			$info['class_1'] = $temp['parent_id'];
		}elseif (C('PRODUCT_CLASS_LEVEL')==4) {
			$info['class_4'] = $product_class_id;
			$temp = M('ProductClass')->field('parent_id')->where($product_class_id)->find();
			$info['class_3'] = $temp['parent_id'];
			$temp = M('ProductClass')->field('parent_id')->where($temp['parent_id'])->find();
			$info['class_2'] = $temp['parent_id'];
			$temp = M('ProductClass')->field('parent_id')->where($temp['parent_id'])->find();
			$info['class_1'] = $temp['parent_id'];
		}
		return $info;
	}
	
	/**
	 * 返回类型对应的字段
	 *
	 * @param int $type 导入类型
	 * @return array
	 */
	public function getExcelFields($type){ 
		$ExcelTemplete	=	include(RUNTIME_PATH.'~ExcelTemplete.php'); 
		foreach((array)$ExcelTemplete[$type] as $k=>$v){   $field[]	=	isset($v[2])?$v[2]:$v[0]; }
		return $field; 
	} 
	
	/**
	 * 导出EXCEL表格
	 *
	 * @param string $main 导入路径	
	 * @param string $type	模板名称
	 * @param int $insert_type	//1替换 2跳过 
	 * @return string
	 */
	public function derivedExcel($main,$type,$file_name,$insert_type=1){
		$return_error['type']	=	1;  
 		if (empty($main) || empty($type)){ return $this->setExcelErrorMsg(1);}  
 		$this->insert_type	=	$insert_type;  
		///虚拟化数据 
		$file	=	RUNTIME_PATH.'Uploads/Excel/'.$file_name.'.xls';
		Vendor('PhpExcel.PHPExcel');
		$result	=	$this->Import_Execl($file);    
		///载入字段
		$field	=	$this->getExcelFields($type); 
                echo json_encode($field);exit;
		///验证导入字段列数量与实际模板列数是否相同 
		if (count($field)!=$result['data'][0]['Cols']){   return $this->setExcelErrorMsg(2); } 
		///判断字段模板是否存在！
		if (!is_array($field)){  return $this->setExcelErrorMsg(3);	} 
//		import("Dzh.FormValid.FormValidDefault");			// 导入验证类
//		$class_form_validate	= D('FormValidDefault');	// 实例化验证类
        $modelExcel	=	$this; 
		$excel_info	=	$this->excel_info;  
		$excel		=	$excel_info[$main];
		$this->excel_max_row	=	$excel['max_row']>0?$excel['max_row']:999; 
		if ($result["data"][0]['Rows']>$this->excel_max_row){ return $this->setExcelErrorMsg(4,$this->excel_max_row); }   
		
		$excel['field']	=	$field;   
		$state			=	1; 
		$execl_data 	= $result["data"][0]["Content"]; 
        unset($execl_data[1]);  
//        $_validate		=	$class_form_validate->getValidate($excel['valid']); //表单验证  
        $model 			= 	D($type);    
        $model_detail	=   D($excel['table_name']);
        $model->isAjax	=	true; 
        $add_auto_no	=	false;
		if (isset($excel) && isset($excel['auto_no']) && isset($excel['action'])){ 
			$max_no			=	$actionModel = A($excel['action'])->getMaxNo($type);
			$max_leng		=	strlen($max_no);
			$add_auto_no	=	$max_leng>0?true:false;
		}
		///预先的动作 
       if (isset($excel['befor_valid'])){     
       		$befor_valid	=	$this->$excel['befor_valid'](&$execl_data,&$excel['replace'],&$excel); 
       		if (is_array($befor_valid) && $befor_valid['type']==false){  return $this->setErrorMsg(4,0,$befor_valid['msg']); } 
       }
		///需要格式化的日期
		$option			= C('_dd_config_'); ///获取格式化基础信息  	
		$define_date	= $option['format_date'];///读取需要 日期格式化的字段 
	   $is_date	=	1;
	   ///验证是否有需要插入日期格式的字段
	   foreach((array)$excel['field'] as $k=>$v){  if (in_array($v,$define_date)){	$format_date[]	=	$v;	$is_date	=	2;	}	   }
		$array_merge	=	false;
		if (is_array($excel['default'])){ $array_merge	=	true; }
		///表单中唯一的验证
		$insertUnique	=	array();   
		///验证+补充信息 ;
        foreach((array)$execl_data as $k=>$v){  
        		foreach((array)$excel['field'] as $key=>$value){    
     		  		$d[$value] 	= $v[$key]; 
     		  		if (isset($excel['replace'][$value]['field'])){   
     		  			if ($excel['replace'][$value]['select']==true){ 
     		  				$defValue	=	$this->getReplaceId(&$v[$key],&$excel['replace'][$value]); 
     		  				$d[$excel['replace'][$value]['field']]	=	empty($defValue)?$excel['replace'][$value]['default_value']:$defValue; 
     		  			}else{
     		  				$d[$excel['replace'][$value]['field']]	=	empty($d[$value])?$excel['replace'][$value]['default_value']:0;
     		  			}  
     		  		}
     		  		///判断是否是日期 如果是=》格式化 
     		  		if ($is_date==2 && in_array($value,$format_date)){ 
     		  			if (!empty($v[$key])){
//     		  				$d[$value]	=	gmdate("Y-m-d",PHPExcel_Shared_Date::ExcelToPHP($v[$key]));  
     		  				$d[$value]	=	$v[$key];  
     		  			}else {
     		  				$d[$value]	=	'';
     		  			}  
     		  		}
     		  		///切割数据 
     		  		if (isset($excel['explode']) && in_array($value,$excel['explode'])){  
     		  			$exploded[]	=	$value;
     		  			$d[$value]	=	explode(',',$v[$key]);
     		  		} 
     		  }
     		   
     		  if ($array_merge){ ///是否有默认值补充   
 		  			$jiaoji	=	array_intersect_key($d,$excel['default']); ///交集
 		  			foreach((array)$jiaoji as $keyJ=>$valueJ){  unset($excel['default'][$keyJ]); }    ///过滤交集的默认值
 		  			$d	=	array_merge($d,$excel['default']);
     		  } 
     		  ///自动补充值
     		  if ($add_auto_no && empty($d[$excel['auto_no']])){ 
					$max_no					= $max_no+1;
					$d[$excel['auto_no']]	= str_pad($max_no,$max_leng,'0',STR_PAD_LEFT); 
					$d['system_auto']		= true;  
			  }else{  
			  		$d['system_auto']		= false;
			  }     
			  ///验证数据
			  $_validdate	= $model->getValidDate();
				if (isset($_validdate)){  
					///客户输入的编号验证是否重复
					if ($d['system_auto']==true){
						$updateInfo	=	$model->where($excel['auto_no'].'=\''.$d[$excel['auto_no']].'\'')->find();
						if ($updateInfo['id']>0){$d['id']	=	$updateInfo['id'];}  
					}  
					///如果表单唯一没有被提取验证过，则获取表验证中唯一字段的值 
					if (!isset($insertUnique[$model->name])){ 
						$validArray = $model->getValidDate(); /// 获取验证规则
						foreach((array)$validArray as $validKey=>$validValue){  
							if (is_array($validValue) && isset($validValue[4]) && $validValue[4]=='unique'){ 
								$insertUnique[$model->name][]	=	 $validValue[0];
							}  
						}
						if (!is_array($insertUnique[$model->name])){ $insertUnique[$model->name]	=	false;} 
					} 
					if($insert_type==1){$model->valid_excel_unique_state	= false;}
					if($type=='Stocktake' || $type=='InitStorage'){
						$wInfo			= M('warehouse')->where('is_default=1')->field('id')->find();
						$default_w_id	= $wInfo['id'];   
						if ($default_w_id<=0){ return $this->setExcelErrorMsg(0,'请设置默认仓库,在重新导入数据'); } 
						if($type=='Stocktake'){
							$d	= array( 	
								'stocktake_no'			=>'',
								'stocktake_date'		=> date("Y-m-d"),
								'warehouse_id'			=>$default_w_id,
								'currency_id'			=>C('currency'),
								'employee_id'			=>0,
								'state'					=>1,
								'create_time'			=>date("Y-m-d H:i:s"),
								'detail'				=> array($d) );   
						}elseif ($type=='InitStorage'){
							$d	= array( 	
									'init_storage_no'		=>'',
									'init_storage_date'		=>date("Y-m-d"),
									'warehouse_id'			=>$default_w_id,
									'currency_id'			=>C('currency'),
									'create_time'			=>date("Y-m-d H:i:s"),
									'detail'				=> array($d)  );   
						}
					}
					$r	= $model->create($d);				/// 调用验证方法 
					if (!$r) { /// 验证失败   
						$error[$k] 	= $model->error;
						if($type=='Stocktake' || $type=='InitStorage'){
							foreach ($d['detail'] as $kk=>&$vv){
								$d	= $vv;
							}
						}
						$insert[$k]	=	$d;
						$state 		=	2;
						break ;		 								/// 验证失败
					} else {    				
						if($type=='Stocktake' || $type=='InitStorage'){
							foreach ($d['detail'] as $kk=>&$vv){
								$d	= $vv;
							}
						}
						/// 验证成功 
						$id	= $model->excel_ids; 
						if ($id['id']>0 && $d['id']<=0){ 
							if ($this->insert_type==2){ continue ;}
							$d['id']	=	$id['id']; 
						}  
						unset($d['system_auto']);
						$insert[$k]	=	$d; 
					} 					
				}else{ 
						unset($d['system_auto']);
						$insert[$k]	=	$d; 
				}
				unset($d); 
       }   
       ///预先的动作   
       if (isset($excel['befor_fn'])){
   	 		if($type == 'InitStorage'){
				addLang('InitStorage');
				$behavior	= new InitStoragePublicBehavior();
				$init_Info	=	array(
							'init_storage_no'		=>'',
							'init_storage_date'		=>date("Y-m-d"),
							'warehouse_id'			=>$default_w_id,
							'currency_id'			=>C('currency'),
							'create_time'			=>date("Y-m-d H:i:s"),
				);  
				$error_info	= $behavior->checkSam(@array_merge($init_Info,array('detail'=>$insert)),true);	
				if(isset($error_info)) return $this->setErrorMsg(4,0,'不能重复添加期初库存,请重试!');
				else $main_info	= $modelExcel->$excel['befor_fn'](&$insert,&$model);
			}else{
       			$main_info	= $modelExcel->$excel['befor_fn'](&$insert,&$model);   
			}
//       		if (is_array($beforError)){   $error[][]['show'] = $beforError['msg']; }
       }    
       ///验证表单是否有错误信息   
       if (is_array($error)){ return $this->setErrorArray($error);} 
       $insertCount	=	0;  ///处理总数量
       ///切割数组
        if (is_array($exploded)){              		 		
        		///特殊处理
 		 		$autoNo	=	array(
			 		 		'class_no'=>'productclass_no',
			 		 		'color_no'=>'color_no',
			 		 		'size_no'=>'size_no',
 		 		); 
         		 foreach((array)$insert as $key=>$value){   
         		 	foreach((array)$value as $key2=>$value2){     
             		 	if (is_array($value2)){ 
							if (is_array($autoNo)){  
								if (in_array($autoNo[$excel['replace'][$key2]['auto_no']],array('color_no','size_no','productclass_no'))){ 
             		 			if (C('setauto_'.$autoNo[$excel['replace'][$key2]['auto_no']])==2){ return $this->setErrorMsg(1,$key,L($excel['replace'][$key2]['auto_no']).',未开启自动编号,请与客服联系');}  
             		 				unset($autoNo[$excel['replace'][$key2]['auto_no']]);
	             		 		}  
							} 
             		 		$detail_insert[$key2][$key]							= $this->explodeInsert($value2,$excel['replace'][$key2]); 
             		 		$end												= end($detail_insert[$key2][$key]); 
             		 		isset($excel['replace'][$key2]['field'])	&&	$insert[$key][$excel['replace'][$key2]['field']]	= $end['id']; 
             		 		if (!isset($del_replace[$key2])){ $delReplace[$key2]	=	$key2;}  
             		 		unset($insert[$key][$key2]);
             		 	}
         		 	}
         		 }
         		///删除使用过的插入信息
				foreach((array)$delReplace as $key=>$value){ unset($excel['replace'][$value]);}   
         }
         if (isset($excel['replace'])){ 
			foreach((array)$excel['replace'] as $key=>$value){    
				///初始化实例化对象 
				$$value['tables']							=	$value['tables']; 
				if (isset($value['action'])){
					$excel['replace'][$key]['max_no']		=	A($value['action'])->_autoMaxNo(0,$$value['tables']);
					$excel['replace'][$key]['leng']			=	strlen($excel['replace'][$key]['max_no']); 
				} 
			} 
			$afterInsert	=	false;   
			foreach((array)$insert as $k=>$v){   
				 foreach((array)$excel['replace'] as $kr=>$vr){  
				 	///判断是否有后续操作
				 	if ($vr['after_insert']==true && $afterInsert==false){ $afterInsert	=	true;}
				 	///判断补充的信息是否有值如果有获取信息 
				 	if (!empty($v[$kr]) && !isset($vr['after_insert'])){ 
			  			$replace_model	=	D($$vr['tables']);   
			  			///如果是查询补充就过滤 
			  			if (!isset($excel['replace'][$kr]['select'])){ 
				  			$v_id	=	$this->getReplaceIdWithExcel($replace_model,$v[$kr],&$excel['replace'][$kr]);    
				  			unset($replace_model);
				  			if ($v_id>0){
				  				$v[$vr['field']]	=	$v_id;
				  			}else{  
				  				$msg	=	 $v[$kr].'不存在,';
				  				return $this->setErrorMsg(2,$k,$msg); 
				  			}
			  			}   
				 	}  
				 }
//				 if($type == 'InitStorage'){
//					addLang('InitStorage');
//					$behavior	= new InitStoragePublicBehavior();
//					$error_info	= $behavior->checkSam(@array_merge($main_info,array('detail'=>$insert)),true);	
//				}
//				if(isset($error_info)) return $this->setErrorMsg(4,0,'不能重复添加期初库存,请重试!');
				 $id	=	$this->excelInsert(&$model,&$v,&$insertUnique,$main_info,$model_detail);  
				 if ($id==false){  return $this->setErrorMsg(2,$k); } 
				 $insertCount++;
				 $id>0	&& $insert[$k]	=	$id;
				 ///执行后插入
				 if ($afterInsert==true){
					 foreach((array)$excel['replace'] as $kr=>$vr){   
					 	///判断补充的信息是否有值如果有获取信息  
					 	if (!empty($v[$kr]) && $vr['after_insert']==true){  
						 	$excel['replace'][$kr]['default'][$excel['replace'][$kr]['field']]	=	$id;  
				  			$replace_model	=	D($$vr['tables']);   
				  			///如果是查询补充就过滤 
				  			if (!isset($excel['replace'][$kr]['select'])){   
					  			$v_id	=	$this->getReplaceIdWithExcel($replace_model,$v[$kr],&$excel['replace'][$kr]);     
				  			}   
					 	}  
					 }				 	
				 } 
				 unset($id);
			} 
         }else{   
              foreach((array)$insert as $k=>$v){    
              	$id	=	$this->excelInsert(&$model,&$v,&$insertUnique);
              	if ($id==false){   return $this->setErrorMsg(2,$k); }    
              	$insertCount++;
              	$id>0	&& $insert[$k]	=	$id;
              	unset($id);
              }                        	
         }
       
		///预先的动作 
		if (isset($excel['after_fn'])){
			$info['insert']	=	$insert;
			$info['detail']	=	$detail_insert;
			$info['excel']	=	$excel;     
			$modelExcel->$excel['after_fn'](&$info);
		}  
		///生成缓存		
		if (isset($excel['dd']) && is_array($excel['dd'])){ foreach((array)$excel['dd'] as $k=>$v){cacheDd($v);} } 
        return $this->setErrorMsg(3,$insertCount);
	}   
	
	/**
	 * 返回错误提示数组信息
	 *
	 * @param array $error
	 * @return array
	 */
	public function setErrorArray($error){
		foreach((array)$error as $key=>$value){  
       			foreach((array)$value as $key2=>$value2){   
       				$return_error['msg']	=	L($value2['field']).$value2['error']; 
					if (isset($value2['show'])){ 
						$errorInfo	=	$this->setErrorMsg(1,$key,$value2['show']); 
						break 2;
					}else{
						$errorInfo	=	$this->setErrorMsg(1,$key); 
						break 2;
					}
//					$errorInfo	=	$this->setErrorMsg(1,$key,L($value2['name']).$value2['value']);  
       			} 
       	}
       	return $errorInfo;
	}
	
	/**
	 * 返回错误提示信息
	 *
	 * @param int $type
	 * @param string $key
	 * @param string $msg
	 * @return array
	 */
	public function setErrorMsg($type=1,$key=0,$msg=null){
		$errorInfo['type']	=	$type;
		switch ($type){
			case 0:///处理操作验证
				$errorInfo['type']	=	false;
				$errorInfo['msg']	=	'第'.$key.'行,数据错误请修改!'.$msg;
				break;
			case 1:///返回行数的错误信息
				$errorInfo['msg']	=	'第'.$key.'行,数据错误请修改.'.$msg;
				break;
			case 2:///返回msg的错误信息
				$errorInfo['msg']	=	'第'.$key.'行,'.$msg.'插入有误,请重新导入,'.$msg; 
				break;
			case 3:///返回msg的错误信息 
				$errorInfo['msg']	=	'成功处理'.$key.'条';  
				break;		 
			case 4:
				$errorInfo['msg']	=	$msg;
				break;
		}
		return $errorInfo; 
	}
	
	/**
	 * Exl解析的错误信息
	 *
	 */
	public function setExcelErrorMsg($type,$message=null){
		$msgType	=	1;
		switch ($type){
			case 0:
				$msgType	=	0;
				$msg		=	$message;	
				break;
			case 1:
				$msg	=	'异常错误,请重新导入';	
				break;
			case 2:
				$msg	=	'导入模板格式错误,请重新导入';	
				break;
			case 3:
				$msg	=	'模板文件出错,请联系客服';	
				break;	
			case 4:
				$msg	=	'太长了,超过'.$message.'个';   
				break;	 
			default:
				$msg	=	'未知错误,请联系客服';	
		}
		return $this->setErrorMsg($msgType,0,$msg);
	}
	
	
	/**
	 * 返回相应需要查询的ID号码
	 *
	 * @param string $name
	 * @param array $replace
	 * @return int
	 */
	public function getReplaceId(&$name,&$replace){ 
		if (!is_object($this->newModel[$replace['tables']])){
			$this->newModel[$replace['tables']]	=	M($replace['tables']);
		} 
		$id = $this->newModel[$replace['tables']]->where($replace['insert_name'].'=\''.$name.'\'')->getField('id'); 
//		echo $this->newModel[$replace['tables']]->getLastSql();
//		exit;
		return $id; 
	}
	
	/**
	 * exl插入信息
	 *
	 * @param object $model
	 * @param array $insert
	 * @return int
	 */
	public function excelInsert(&$model,&$insert,&$insertUnique=array(),$main_info=null,$model_detail){ 
		///过滤掉数组中空值的部分
		$insert = array_diff($insert, array(null));  
		if ($insert['id']>0){ 
		 	///插入信息 或者 update
		 	if ($this->insert_type<>2){ 
		 		if(is_array($main_info)){
					$main_info['detail']	= array($insert);
					if($model->create($main_info)){
						$id	= $model_detail->save($insert); 
					}
				}else{ 
			 		if ($model->create($insert)) {	
			 			$model->save();   
			 		}
				}
		 		$id = $insert['id'];
		 	} 
		}else{    
			///插入前再一次判断唯一值是否已存在~！如果存在直接跳过 
			if (is_array($insertUnique[$model->name])){  
				$validName	=	$insertUnique[$model->name];
				$insertUniqueWhere	=	'';
				foreach((array)$validName as $key=>$value){  if (isset($insert[$value])){ $insertUniqueWhere[]=$value.'=\''.$insert[$value].'\'  '; } }  
				$info		=	$model->where(join(' or ',$insertUniqueWhere))->find();
				if (is_array($info)){ return $info['id']; }  
			}
			if(is_array($main_info)){
				$main_info['detail']	= array($insert);
				if($model->create($main_info)){
					unset($insert['product_no'],$insert['color_no'],$insert['size_no']);
					$id	= $model_detail->add($insert); 
				}
			}else{  
				if ($model->create($insert)) {	  
				 	///插入信息 或者 update  
				 	$id	= $model->add(); 
				}
			}
		}
		return $id; 
	}
 
	
	/**
	 * 关联插入
	 *
	 * @param array $info
	 * @param array $replace
	 * @return array
	 */
	public function explodeInsert($info,$replace){   
		if (!is_array($info)){ return ;}  
		$model	=	M($replace['tables']);   
		if (isset($replace['action'])){
			$replace['max_no']			=	A($replace['action'])->_autoMaxNo(0,$replace['tables']);  
			$replace['leng']			=	strlen($replace['max_no']);   			
		} 
		$pareant_id	=	0;
		foreach((array)$info as $key=>$value){ 
			///类别临时特殊处理
			if ($replace['tables']=='product_class'){  $replace['default']	=	array_merge($replace['default'],array('class_level'=>$key+1,'parent_id'=>$pareant_id));}
			$insert[$key]['name']	=	$value;
			$pareant_id	=	$insert[$key]['id']		=	$this->getReplaceIdWithExcel($model,$value,$replace);
		}    
		  
		return $insert; 
	}
	
	/**
	 * 返回关联ID
	 *
	 * @param object $model
	 * @param string $value
	 * @param array $array
	 * @return int
	 */
	public function getReplaceIdWithExcel($model,$value,&$array){ 
		$where	=	$array['insert_name'].'=\''.$value.'\'';
		$info	=	$model->where($where)->find();    
//		echo $model->getLastSql();  
//		echo '<br>';
		///如果已经存在返回ID 
		if (is_array($info) || $array['select']==true){ 
			$id	=	$info['id'];
		}else { 
			isset($array['insert_name'])	&&	$insert[$array['insert_name']]	=	$value; 
			if (isset($array['auto_no'])){
				$array['max_no']	=	$max_no	=	str_pad($array['max_no']+1,$array['leng'],'0',STR_PAD_LEFT);
				$insert[$array['auto_no']]	=	$max_no;
			}  
			if (isset($array['default']) && is_array($array)){	$insert =	array_merge($insert,$array['default']);}  
			is_array($insert)	&&	$id	=	$model->add($insert);
		}
		return $id;
	}
    
   function Import_Execl($file){
                if(!file_exists($file)){
                        return array("error"=>1);
                }
                Vendor("PHPExcel.PHPExcel");
                $PHPExcel = new PHPExcel();  
                $PHPReader = new PHPExcel_Reader_Excel2007();                    
                if(!$PHPReader->canRead($file)){      
                        $PHPReader = new PHPExcel_Reader_Excel5(); 
                        if(!$PHPReader->canRead($file)){      
                                return array("error"=>2);
                        }
                }
                $PHPExcel = $PHPReader->load($file);
                $SheetCount = $PHPExcel->getSheetCount();
                for($i=0;$i<$SheetCount;$i++){
                        $currentSheet = $PHPExcel->getSheet($i);
                        $allColumn = $this->ExcelChange($currentSheet->getHighestColumn());   
                        $allRow = $currentSheet->getHighestRow();  
                        $array[$i]["Title"] =  $currentSheet->getTitle();
                        $array[$i]["Cols"] = $allColumn;
                        $array[$i]["Rows"] = $allRow;
                        $arr = array();
                        for($currentRow = 1 ;$currentRow<=$allRow;$currentRow++){
                                $row = array();
                                for($currentColumn=0;$currentColumn<$allColumn;$currentColumn++){ 
                                        $cell 				 = $currentSheet->getCellByColumnAndRow($currentColumn,$currentRow); 
                                        $row[$currentColumn] = $cell->getValue(); 
//                                        if($cell->getDataType()==PHPExcel_Cell_DataType::TYPE_NUMERIC){   
////											   $cellstyleformat=$cell->getParent()->getStyle( $cell->getCoordinate() )->getNumberFormat();  
////										       $formatcode=$cellstyleformat->getFormatCode();  
//										       $formatcode='yyyy-mm-dd';   
//										       if (preg_match('/^(\[\$[A-Z]*-[0-9A-F]*\])*[hmsdy]/i', $formatcode)) {    
//										             $row[$currentColumn]=gmdate("Y-m-d", PHPExcel_Shared_Date::ExcelToPHP($row[$currentColumn]));  
//										       }else{   
//										             $row[$currentColumn]=PHPExcel_Style_NumberFormat::toFormattedString($row[$currentColumn],$formatcode);  
//										       }  
//                                        }  
                                } 
                                $arr[$currentRow] = $row;
                        } 
                        $array[$i]["Content"] = $arr;
                }
                spl_autoload_register(array('Think','autoload'));///必须的，不然ThinkPHP和PHPExcel会冲突
                unset($currentSheet);
                unset($PHPReader);
                unset($PHPExcel);                
//                unlink($file);   //删除上传的文件     
                return array("error"=>0,"data"=>$array);
        }

	 public function ExcelChange($str){///配合Execl批量导入的函数
                $len = strlen($str)-1;
                $num = 0;
                for($i=$len;$i>=0;$i--){
                        $num += (ord($str[$i]) - 64)*pow(26,$len-$i);
                }
                return $num;
      }
        
     public function import(){
                if(isset($_FILES["import"]) && ($_FILES["import"]["error"] == 0)){
                        $result = $this->Import_Execl($_FILES["import"]["tmp_name"]);
                        if($this->Execl_Error[$result["error"]] == 0){
                                $execl_data = $result["data"][0]["Content"];
                                unset($execl_data[1]);
                                $data = D("Data");
                                foreach($execl_data as $k=>$v){
                                        $d["serial_no"] 	= $v[0];
                                        $d["check_no"] 		= $v[1];
                                        $d["work_no"] 		= $v[2];
                                        $d["class_name"] 	= $v[3];
                                        $d["user_name"] 	= $v[4];
                                        $d["new_class"] 	= $v[5];
                                        $d["error_level"] 	= $v[6];
                                        $data->data($d)->add();
                                }                                
                                $this->success($this->Execl_Error[$result["error"]]);
                        }else{
                                $this->error($this->Execl_Error[$result["error"]]);
                        }
                }else{
                        $this->error("上传文件失败");
                }
        }   
}
?>